package com.nanjia.boot.shared.file.controller;

import com.nanjia.boot.common.result.Result;
import com.nanjia.boot.shared.file.service.FileService;
import com.nanjia.boot.shared.file.model.FileInfo;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.enums.ParameterIn;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Operation;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.nio.file.Files;

/**
 * 文件控制层
 *
 * @author Ray.Hao
 * @since 2022/10/16
 */
@Tag(name = "07.文件接口")
@RestController
@RequestMapping("/api/v1/files")
@RequiredArgsConstructor
@Slf4j
public class FileController {

    private final FileService fileService;
    @Value("${oss.local.storage-path}")
    private String storagePath;
    @PostMapping
    @Operation(summary = "文件上传")
    public Result<FileInfo> uploadFile(
            @Parameter(
                    name = "file",
                    description = "表单文件对象",
                    required = true,
                    in = ParameterIn.DEFAULT,
                    schema = @Schema(name = "file", format = "binary")
            )
            @RequestPart(value = "file") MultipartFile file
    ) {
        FileInfo fileInfo = fileService.uploadFile(file);
        return Result.success(fileInfo);
    }

    @DeleteMapping
    @Operation(summary = "文件删除")
    @SneakyThrows
    public Result<?> deleteFile(
            @Parameter(description = "文件路径") @RequestParam String filePath
    ) {
        boolean result = fileService.deleteFile(filePath);
        return Result.judge(result);
    }

    @GetMapping("/get/**")  // 支持多级路径
    @Operation(summary = "文件下载")
    public void downloadFile(HttpServletRequest request, HttpServletResponse response) throws IOException {
        // 获取请求路径（去掉/api/v1/files前缀）
        String path = request.getRequestURI().substring("/api/v1/files/get".length());
        log.info("path:{}", path);
        int queryIndex = path.indexOf("?");
        if (queryIndex != -1) {
            path = path.substring(0, queryIndex);
        }
        log.info("path:{}", path);
        log.info("storagePath:{}", storagePath);
        log.info("Path:{}", storagePath + path);
        File file = new File(storagePath + path);
        if (file.exists()) {
            // 自动检测MIME类型
            String contentType = Files.probeContentType(file.toPath());
            response.setContentType(contentType != null ? contentType : "application/octet-stream");

            try (InputStream is = new FileInputStream(file);
                 OutputStream os = response.getOutputStream()) {
                byte[] buffer = new byte[1024];
                int bytesRead;
                while ((bytesRead = is.read(buffer)) != -1) {
                    os.write(buffer, 0, bytesRead);
                }
            }
        } else {
            response.setStatus(HttpServletResponse.SC_NOT_FOUND);
        }
    }
}
